package com.custom.common.sha256;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @ClassName: Md5Verify
 * @description:
 * @author: liukui
 * @date: 2018/11/17 16:12
 * @version: 1.0
 */
public class Md5Verify {
    private static final String verifyKey = "sign";
    private static final Logger LOGGER = LoggerFactory.getLogger(Md5Verify.class);

    public Md5Verify() {
    }

    public static String md5sum(String source) {
        return DigestUtils.md5Hex(source);
    }

    public static Boolean verifyMd5(Map<String, String> params, String secretKey) {
        String requestSignData = (String)params.get("sign");
        params.remove("sign");
        return verifyMd5(params, secretKey, requestSignData);
    }

    public static Boolean verifyMd5(Map<String, String> params, String secretKey, String requestSignData) {
        params.remove("sign");
        String data = createLinString(params);
        String signData = md5sum(data + secretKey);
        if(signData.equals(requestSignData)) {
            return Boolean.valueOf(true);
        } else {
            LOGGER.debug("md5 not same,reqmd5:" + requestSignData + ",server calc md5:" + signData);
            return Boolean.valueOf(false);
        }
    }

    public static String createLinString(Map<String, String> params) {
        List<String> keys = new ArrayList(params.keySet());
        Collections.sort(keys);
        String result = "";

        String key;
        for(Iterator i$ = keys.iterator(); i$.hasNext(); result = result + key + "=" + (String)params.get(key) + "&") {
            key = (String)i$.next();
        }

        if(keys.size() > 0) {
            result = result.substring(0, result.length() - 1);
        }

        return result;
    }
}
